package com.uziot.bucket.common.util.file;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * @author shidt
 * @version V1.0
 * @className FileFileMonitor
 * @date 2020-04-23 08:52:37
 * @description
 */
@Slf4j
public class FileMonitor {
    /**
     * 上次文件大小
     */
    private static long lastTimeFileSize = 0;
    private String logFilePath;

    public FileMonitor() {
    }

    public FileMonitor(String logFilePath) {
        //初始化对象的时候，记录已经有的日志长度，不读取历史记录
        File file = new File(logFilePath);
        lastTimeFileSize = file.length();
        log.info("当前日志监控启动，初始化标记历史记录行位置：{}", lastTimeFileSize);
        this.logFilePath = logFilePath;
    }

    public String getLogFilePath() {
        return logFilePath;
    }

    public static long getLastTimeFileSize() {
        return lastTimeFileSize;
    }

    public static void setLastTimeFileSize(long lastTimeFileSize) {
        log.info("设置当前日志读取行位置：" + lastTimeFileSize);
        FileMonitor.lastTimeFileSize = lastTimeFileSize;
    }

    public void setLogFilePath(String logFilePath) {
        //初始化对象的时候，记录已经有的日志长度，不读取历史记录
        File file = new File(logFilePath);
        lastTimeFileSize = file.length();
        log.info("当前日志监控位置发生变更，初始化标记历史记录行位置：{}", lastTimeFileSize);
        this.logFilePath = logFilePath;
    }

    public List<String> seekFile() throws IOException {
        File file = new File(logFilePath);
        return this.seekFile(file);
    }

    /**
     * 实时输出日志信息
     *
     * @param logFile 日志文件
     * @throws IOException IOException
     */
    public List<String> seekFile(File logFile) throws IOException {
        //指定文件可读可写
        final RandomAccessFile randomFile = new RandomAccessFile(logFile, "rw");
        try {
            //获得变化部分的
            randomFile.seek(lastTimeFileSize);
            String tmp;
            ArrayList<String> lineList = new ArrayList<>();
            while ((tmp = randomFile.readLine()) != null) {
                String line = new String(tmp.getBytes("ISO8859-1"));
                lineList.add(line);
            }
            lastTimeFileSize = randomFile.length();
            return lineList;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
